<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useAntdForm, useFormRules } from '@/hooks/common/form';
import { fetchCreateUser, fetchGetAllRoles, fetchUpdateUser } from '@/service/api';
import { $t } from '@/locales';
import { enableStatusOptions, userGenderOptions } from '@/constants/business';

defineOptions({
  name: 'UserOperateDrawer'
});

interface Props {
  /** the type of operation */
  operateType: AntDesign.TableOperateType;
  /** the edit row data */
  rowData?: Api.SystemManage.User;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('open', {
  default: false
});

const { formRef, validate, resetFields } = useAntdForm();
const { defaultRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: Record<AntDesign.TableOperateType, string> = {
    add: $t('page.manage.user.addUser'),
    edit: $t('page.manage.user.editUser')
  };
  return titles[props.operateType];
});

type Model = {
  userName: string;
  userGender: Api.SystemManage.UserGender;
  nickName: string;
  userPhone: string;
  userEmail: string;
  password?: string;
  roles: string[];
  status: Api.Common.EnableStatus;
};

const model = ref<Model>({
  userName: '',
  userGender: '1',
  nickName: '',
  userPhone: '',
  userEmail: '',
  roles: [], // 必须是数组
  status: '1'
});

function createDefaultModel(): Model {
  return {
    userName: '',
    userGender: '1',
    nickName: '',
    userPhone: '',
    userEmail: '',
    password: '',
    roles: [],
    status: '1'
  };
}

type RuleKey = Extract<keyof Model, 'userName' | 'status' | 'password'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  userName: defaultRequiredRule,
  status: defaultRequiredRule,
  password: defaultRequiredRule
};

/** the enabled role options */
const roleOptions = ref<CommonType.Option<string>[]>([]);

async function getRoleOptions() {
  const { error, data } = await fetchGetAllRoles();

  if (!error) {
    const options = data.map(item => ({
      label: item.roleName,
      value: item.roleCode
    }));

    roleOptions.value = options;
    // console.log('角色选项:', options);
  } else {
    console.error('加载角色选项失败:', error);
  }
}

function handleInitModel() {
  model.value = createDefaultModel();

  if (props.operateType === 'edit' && props.rowData) {
    // 处理用户角色数据，将逗号分隔的字符串转换为数组
    const userData = { ...props.rowData } as any;

    if (typeof userData.roles === 'string') {
      if (userData.roles.startsWith('[') && userData.roles.endsWith(']')) {
        try {
          userData.roles = JSON.parse(userData.roles);
        } catch {
          userData.roles = [];
        }
      } else if (userData.roles.includes(',')) {
        userData.roles = userData.roles.split(',').map((r: string) => r.trim());
      } else if (userData.roles) {
        userData.roles = [userData.roles];
      } else {
        userData.roles = [];
      }
    }

    Object.assign(model.value, userData);
  }
}

function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();

  try {
    const submitData = { ...model.value };

    // 将roles数组转换为JSON字符串
    if (submitData.roles && Array.isArray(submitData.roles) && submitData.roles.length > 0) {
      (submitData as any).roles = JSON.stringify(submitData.roles);
    } else {
      (submitData as any).roles = JSON.stringify([]);
    }

    if (props.operateType === 'add') {
      // Convert roles to userRoles and remove the roles field
      const { roles, ...userData } = submitData;
      const createUserData = {
        ...userData,
        userRoles: roles
      };
      const { error: err } = await fetchCreateUser(createUserData as any);
      if (!err) {
        window.$message?.success($t('common.addSuccess'));
        closeDrawer();
        emit('submitted');
      }
    } else {
      const userId = (props.rowData as any)?.id;
      // 编辑用户时，如果密码为空，则不包含在提交数据中
      const updateData = { ...submitData };
      if (!updateData.password) {
        delete updateData.password;
      }
      const { error: err } = await fetchUpdateUser(userId, updateData as any);
      if (!err) {
        window.$message?.success($t('common.updateSuccess'));
        closeDrawer();
        emit('submitted');
      }
    }
  } catch (error: any) {
    console.error('提交失败:', error);
    window.$message?.error('操作失败');
  }
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    resetFields();
    getRoleOptions();
  }
});
</script>

<template>
  <ADrawer v-model:open="visible" :title="title" :width="360">
    <AForm ref="formRef" layout="vertical" :model="model" :rules="rules" name="user_operate_drawer">
      <AFormItem :label="$t('page.manage.user.userName')" name="userName">
        <AInput v-model:value="model.userName" :placeholder="$t('page.manage.user.form.userName')" />
      </AFormItem>
      <AFormItem :label="$t('page.manage.user.password')" name="password">
        <AInputPassword v-model:value="model.password" :placeholder="$t('page.manage.user.form.password')" />
      </AFormItem>
      <AFormItem :label="$t('page.manage.user.userGender')" name="userGender">
        <ARadioGroup v-model:value="model.userGender">
          <ARadio v-for="item in userGenderOptions" :key="item.value" :value="item.value">
            {{ $t(item.label) }}
          </ARadio>
        </ARadioGroup>
      </AFormItem>
      <AFormItem :label="$t('page.manage.user.nickName')" name="nickName">
        <AInput v-model:value="model.nickName" :placeholder="$t('page.manage.user.form.nickName')" />
      </AFormItem>
      <AFormItem :label="$t('page.manage.user.userPhone')" name="userPhone">
        <AInput v-model:value="model.userPhone" :placeholder="$t('page.manage.user.form.userPhone')" />
      </AFormItem>
      <AFormItem :label="$t('page.manage.user.userEmail')" name="email">
        <AInput v-model:value="model.userEmail" :placeholder="$t('page.manage.user.form.userEmail')" />
      </AFormItem>
      <AFormItem :label="$t('page.manage.user.userStatus')" name="status">
        <ARadioGroup v-model:value="model.status">
          <ARadio v-for="item in enableStatusOptions" :key="item.value" :value="item.value">
            {{ $t(item.label) }}
          </ARadio>
        </ARadioGroup>
      </AFormItem>
      <AFormItem :label="$t('page.manage.user.userRole')" name="roles">
        <ASelect
          v-model:value="model.roles"
          mode="multiple"
          :options="roleOptions"
          :placeholder="$t('page.manage.user.form.userRole')"
          @change="
            (val: any) => {
              console.log('ASelect change:', typeof val, val);
            }
          "
        />
        <!-- 调试信息 -->
      </AFormItem>
    </AForm>
    <template #footer>
      <ASpace :size="16">
        <AButton @click="closeDrawer">{{ $t('common.cancel') }}</AButton>
        <AButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</AButton>
      </ASpace>
    </template>
  </ADrawer>
</template>

<style scoped></style>
